<template>
  <div>
    <a-button type="primary" style="margin-top: 20px" @click="editModal(0)">新建</a-button>
    <div style="margin-top: 20px">
      <a-table :pagination="false" :columns="columns" :data-source="roleTableList" rowKey="id">
      <span slot="state" slot-scope="state">
      <a-tag :color="state === -1 ? 'red' : 'cyan'">
        {{ state === -1 ? '禁用' : '使用中' }}
      </a-tag>
    </span>
        <span slot="action" slot-scope="text, record">
      <a-button type="primary" icon="edit" size="small" @click="editModal(record)"></a-button>
      <a-divider type="vertical" />
          <a-button type="primary" icon="safety" size="small" @click="permissionModal(record.id)">权限</a-button>
    </span>
      </a-table>
      <div style="margin-top: 20px;text-align: center">
        <a-pagination v-model="current" :page-size="pageSize" :total="total" @change="changePage"/>
      </div>
    </div>
    <div>
      <a-modal v-model="visible" title="编辑" @ok="handleOk" @cancel="handleCancel">
        <a-form :form="form">

          <a-form-item>
            <a-input v-if="mdl.id > 0" v-decorator="['id', { initialValue: mdl.id } ]" hidden/>
          </a-form-item>
          <a-form-item>
            <a-input v-decorator="['userIdCreate', { initialValue: mdl.userIdCreate } ]" hidden/>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="角色名称">
            <a-input
              v-decorator="['roleName',{ initialValue: mdl.roleName },{rules: [{required: true,message: '请填写角色名称'}]}]"/>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="父级"
          >
            <a-select v-decorator="['merchantId',{initialValue: mdl.merchantId}]">
              <a-select-option :value="0">所属商户</a-select-option>
              <a-select-option v-for="(item, index) in parentMerchants" :value="item.id" :key="index">{{ item.merchantName }}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="是否启用"
          >
            <a-radio-group v-decorator="['state', { initialValue: mdl.state}]">
              <a-radio :value="1">
                启用
              </a-radio>
              <a-radio :value="-1">
                禁用
              </a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="备注"
            hasFeedback
          >
            <a-textarea
              :rows="5"
              placeholder="..."
              id="remark"
              v-decorator="['remark', {initialValue: mdl.remark}]"
            />
          </a-form-item>

        </a-form>
      </a-modal>
    </div>
    <div>
      <a-modal v-model="pimVisible" title="权限编辑" @ok="handleRoleMenuOk" @cancel="handleRoleMenuCancel">
        <template>
          <div v-for="(item, index) in rights">

              <div style="margin-top: 20px">
                <label>
                  <input type="checkbox" :value="item.id" :checked="item.check" @change="checkGroup(index)"/>
                </label>
                <span style="cursor:pointer" @click="checkGroup(index)">{{ item.name }}</span>
              </div>
            <div>
              <div class="check-box" v-for="(child, cIndex) in item.children">
                <input type="checkbox" :value="child.id" :checked="child.check"  @change="checkOne(index, cIndex)">
                <span v-if="child.check" style="cursor:pointer;color:#1890ff" @click="checkOne(index, cIndex)">{{ child.name }}</span>
                <span v-else style="cursor:pointer;" @click="checkOne(index, cIndex)">{{ child.name }}</span>
              </div>
            </div>
            </div>
        </template>
      </a-modal>
    </div>
  </div>

</template>

<script>
  import { getMerchantList, getRoleList, saveUpdateRole, getRoleRights, saveRoleMenus } from "../../api/system";

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '名称',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '商户',
      key: 'merchantName',
      dataIndex: 'merchantName'
    },
    {
      title: '状态',
      key: 'state',
      dataIndex: 'state',
      scopedSlots: {customRender: 'state'},
    },
    {
      title: '备注',
      key: 'remark',
      dataIndex: 'remark'
    },
    {
      title: '操作',
      key: 'action',
      scopedSlots: {customRender: 'action'},
    },
  ];
  export default {
    name: "RoleList",
    data() {
      return {
        labelCol: {
          xs: {span: 24},
          sm: {span: 5}
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 12}
        },
        visible: false,
        pimVisible: false,
        mdl: {
          merchantId: 0,
          roleName: '',
          state: 1,
          remark: ''
        },
        form: '',
        current: 1,
        pageSize: 10,
        total: 0,
        columns,
        roleTableList: [],
        parentMerchants: [],
        currentRoleId: 0,
        originRights: [],
        rights: [],
        rightsChecked: []
      }
    },
    mounted() {
      this.roleList()
    },
    methods: {
      async changePage() {
        this.roleTableList = []
        this.roleList()
      },
      async roleList() {
        let params = {
          pageNo: this.current,
          pageSize: this.pageSize
        }
        const result = await getRoleList(params)
        let pageInfo = result.data.page
        this.total = pageInfo.totalPage
        this.roleTableList = pageInfo.list
      },
      async merchantList() {
        const result = await getMerchantList({pageNo:1,pageSize:100})
        let pageInfo = result.data.page
        this.parentMerchants = pageInfo.list
      },
      editModal(record) {
        this.mdl = {}
        this.mdl = Object.assign({}, record === 0 ? this.mdl : record)
        this.merchantList()
        this.form = this.$form.createForm(this)
        this.visible = true
      },
      async permissionModal(roleId) {
        this.rights = []
        this.currentRoleId = 0
        const result = await getRoleRights(roleId)
        this.currentRoleId = roleId
        this.rights = result.data.roleRights
        this.originRights = result.data.roleRights
        this.pimVisible = true
      },
      handleOk() {
        this.form.validateFields(async (err, values) => {
          const result = await saveUpdateRole(values)
          if (result.code > 0) {
            this.$ms('保存成功')
            this.form = this.$form.createForm(this)
            this.visible = false
            this.roleList()
          } else {
            this.$me(result.message)
          }
        })
      },
      handleCancel() {
        this.form = this.$form.createForm(this)
      },
      async handleRoleMenuOk() {
        if (this.currentRoleId <=0) {
          this.$me("参数错误")
          this.handleRoleMenuCancel()
          this.pimVisible = false
          return
        }
        const result = await saveRoleMenus({ roleId: this.currentRoleId,menuIds: this.rightsChecked})
        if (result.code > 0) {
          this.$ms("保存成功")
          this.pimVisible = false
        } else {
          this.$me("保存失败")
        }
      },
      // 权限对话框关闭
      handleRoleMenuCancel() {

      },
      // 选取组
      checkGroup(index) {
        const arr = this.rights[index]
        // 选中的父级
        this.$set(this.rights[index], 'check', !this.rights[index].check)
        if (this.rights[index].children && arr.children.length > 0) {
          for (let j = 0; j < arr.children.length; j++) {
            this.$set(this.rights[index].children[j], 'check', this.rights[index].check)
          }
        }
        this.checkRightsChecked()
      },
      // 单个选择
      checkOne(parentIndex, childIndex) {
        // 选中父级
        if (!this.rights[parentIndex].check){
          this.$set(this.rights[parentIndex], 'check', !this.rights[parentIndex].check)
        }
        // 当前选中
        this.$set(this.rights[parentIndex].children[childIndex], 'check', this.rights[parentIndex].check)
        this.checkRightsChecked()
      },
      // 遍历出已选菜单
      checkRightsChecked() {
        this.rightsChecked = []
        this.rights.map(item => {
          if (item.check){
            this.rightsChecked.push(item.id)
            item.children.map(child => {
              if (child.check) {
                this.rightsChecked.push(child.id)
              }
            })
          }
        })
      }
    }
  }
</script>

<style scoped>
  .check-box{
    margin-top: 10px;
    display: inline-block;
    box-sizing: border-box;
    cursor: pointer;
    position: relative;
    padding-left: 25px;
    padding-right: 20px;
  }
</style>
